<template>
  <div class="chat-container">
    <div class="chat-messages" ref="chatMessages">
      <div v-for="(message, index) in messages" :key="index"
           :class="['message', message.type]">
        <div class="message-content">{{ message.content }}</div>

        <!-- 快速推荐按钮，当AI询问过多细节而不直接推荐医生时显示 -->
        <div v-if="message.needsQuickRecommendation" class="quick-recommendation">
          <p class="quick-tip">AI正在收集详细信息。如果您希望立即获取医生推荐，请点击下方按钮：</p>
          <button @click="getQuickRecommendation(index)" class="quick-recommend-btn">
            <span class="recommend-icon">🔍</span>
            快速获取医生推荐
          </button>
        </div>

        <!-- 添加取消挂号按钮，仅显示在挂号成功消息下方 -->
        <div v-if="message.role === 'system' && message.content && message.content.includes('挂号成功')" class="booking-actions">
          <button @click="showCancelBookingConfirm(message)" class="cancel-booking-btn">
            <span class="cancel-icon">✕</span>
            取消预约
          </button>
        </div>

        <!-- 显示医生列表 -->
        <div v-if="message.doctors && message.doctors.length > 0" class="doctor-list">
          <h3>推荐医生：</h3>

          <!-- 表格形式展示医生信息 -->
          <table class="doctor-table">
            <thead>
              <tr>
                <th class="doctor-name-column">医生姓名</th>
                <th>所属医院</th>
                <th>科室</th>
                <th>职称</th>
                <th>专长</th>
                <th>挂号费</th>
                <th>接诊状态</th>
                <th class="action-column">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(doctor, dIndex) in message.doctors" :key="dIndex">
                <td class="doctor-name-column">
                  <div class="doctor-name-cell">
                    <span class="doctor-avatar">{{ doctor.realName ? doctor.realName.charAt(0) : '医' }}</span>
                    <span class="doctor-fullname">{{ doctor.realName || '未知姓名' }}</span>
                  </div>
                </td>
                <td>{{ doctor.hospital || '未知医院' }}</td>
                <td>{{ doctor.department || '未知科室' }}</td>
                <td>{{ doctor.title || '医生' }}</td>
                <td>{{ doctor.speciality || '未知专长' }}</td>
                <td>{{ doctor.doctorPrice ? doctor.doctorPrice + '元' : '请咨询' }}</td>
                <td>
                  <span :class="['status-badge', Number(doctor.doctorState) === 1 ? 'status-available' : 'status-unavailable']">
                    {{ Number(doctor.doctorState) === 1 ? '待接诊' : '不可接诊' }}
                  </span>
                </td>
                <td class="action-column">
                  <button
                    class="select-doctor-btn"
                    @click="selectDoctor(doctor)"
                    :class="{ 'disabled': Number(doctor.doctorState) !== 1 }"
                    :disabled="Number(doctor.doctorState) !== 1"
                  >
                    {{ Number(doctor.doctorState) === 1 ? '挂号' : '不可挂号' }}
                  </button>
                </td>
              </tr>
            </tbody>
          </table>

          <!-- 移动端视图 - 在窄屏设备上使用卡片布局 -->
          <div class="doctor-cards-mobile">
            <div v-for="(doctor, dIndex) in message.doctors" :key="dIndex" class="doctor-card">
              <div class="doctor-header">
                <span class="doctor-name">{{ doctor.realName || '未知姓名' }}</span>
                <span class="doctor-title">{{ doctor.title || '医生' }}</span>
              </div>
              <div class="doctor-info">
                <p><label>医院：</label><span>{{ doctor.hospital || '未知医院' }}</span></p>
                <p><label>科室：</label><span>{{ doctor.department || '未知科室' }}</span></p>
                <p><label>专长：</label><span>{{ doctor.speciality || '未知专长' }}</span></p>
                <p v-if="doctor.careerExperience"><label>经历：</label><span>{{ doctor.careerExperience }}</span></p>
                <p v-if="doctor.Introduction"><label>简介：</label><span>{{ doctor.Introduction }}</span></p>
                <p><label>挂号费：</label><span>{{ doctor.doctorPrice ? doctor.doctorPrice + '元' : '请咨询' }}</span></p>
                <p><label>状态：</label>
                  <span :class="['status-badge', Number(doctor.doctorState) === 1 ? 'status-available' : 'status-unavailable']">
                    {{ Number(doctor.doctorState) === 1 ? '待接诊' : '不可接诊' }}
                  </span>
                </p>
              </div>
              <button class="book-btn"
                @click="selectDoctor(doctor)"
                :class="{ 'disabled': Number(doctor.doctorState) !== 1 }"
                :disabled="Number(doctor.doctorState) !== 1"
              >
                {{ Number(doctor.doctorState) === 1 ? '选择此医生' : '不可接诊' }}
              </button>
            </div>
          </div>
        </div>

        <!-- 如果消息中包含医生信息但没有被解析出来，提供手动转换按钮 -->
        <div v-if="message.content && (message.content.includes('医生') || message.content.includes('灰太狼') || message.content.includes('红太狼')) && (!message.doctors || message.doctors.length === 0)" class="convert-doctor-info">
          <button @click="manuallyParseDoctor(message)" class="convert-btn">
            <span class="convert-icon">📋</span>
            将医生信息转换为表格显示
          </button>
        </div>
      </div>
    </div>

    <!-- 医生确认和支付模态框 -->
    <div v-if="showDoctorConfirm" class="doctor-confirm-modal">
      <div class="doctor-confirm-content">
        <h3>确认挂号信息</h3>
        <div class="doctor-details">
          <p><strong>医生姓名：</strong> {{ selectedDoctor.realName }}</p>
          <p><strong>所属医院：</strong> {{ selectedDoctor.hospital || '未知医院' }}</p>
          <p><strong>所属科室：</strong> {{ selectedDoctor.department }}</p>
          <p><strong>职称：</strong> {{ selectedDoctor.title }}</p>
          <p v-if="selectedDoctor.speciality"><strong>专长：</strong> {{ selectedDoctor.speciality }}</p>
          <p v-if="selectedDoctor.careerExperience"><strong>经历：</strong> {{ selectedDoctor.careerExperience }}</p>
          <p v-if="selectedDoctor.Introduction"><strong>简介：</strong> {{ selectedDoctor.Introduction }}</p>
          <p><strong>挂号费用：</strong> {{ selectedDoctor.doctorPrice ? selectedDoctor.doctorPrice + '元' : '请咨询' }}</p>

          <div class="date-selection">
            <p><strong>选择就诊日期：</strong></p>
            <div class="date-options">
              <div
                v-for="date in dateOptions"
                :key="date.value"
                :class="['date-option', { 'selected': selectedDate === date.value }]"
                @click="selectedDate = date.value"
              >
                {{ date.label }}
              </div>
            </div>
          </div>

          <p><strong>选择就诊时段：</strong></p>
          <div class="time-selection">
            <div
              v-for="time in timeSlots"
              :key="time.value"
              :class="['time-option', { 'selected': selectedTimeSlot === time.value }]"
              @click="selectedTimeSlot = time.value"
            >
              {{ time.label }}
            </div>
          </div>
        </div>
        <div class="button-group">
          <button class="register-now-btn primary" @click="proceedToPayment">
            <span class="register-icon">✓</span>
            立即挂号
          </button>
          <button class="cancel-btn secondary" @click="cancelSelection">取消</button>
        </div>
      </div>
    </div>

    <!-- 支付界面模态框 -->
    <div v-if="showPayment" class="payment-modal">
      <div class="payment-content">
        <h3>挂号费用支付</h3>
        <p class="payment-description">
          您正在为{{ selectedDoctor.realName || '所选医生' }}的就诊预约付款，请选择支付方式：
        </p>
        <div class="payment-methods">
          <div
            v-for="(method, index) in paymentMethods"
            :key="index"
            :class="['payment-method', { 'selected': selectedPaymentMethod === method.id }]"
            @click="selectedPaymentMethod = method.id"
          >
            <img :src="method.icon" :alt="method.name" class="payment-icon">
            <span>{{ method.name }}</span>
          </div>
        </div>
        <div class="payment-summary">
          <div class="payment-item">
            <span>挂号费：</span>
            <span>{{ selectedDoctor.doctorPrice ? selectedDoctor.doctorPrice + '元' : '请咨询' }}</span>
          </div>
          <div class="payment-item">
            <span>就诊时间：</span>
            <span>{{ selectedDate }} {{ selectedTimeSlot }}</span>
          </div>
        </div>
        <div class="payment-actions">
          <button class="confirm-payment-btn" @click="confirmPayment">确认支付 {{ selectedDoctor.doctorPrice ? selectedDoctor.doctorPrice + '元' : '请咨询' }}</button>
          <button class="cancel-btn" @click="showPayment = false">取消</button>
        </div>
      </div>
    </div>

    <!-- 取消挂号确认模态框 -->
    <div v-if="showCancelConfirm" class="cancel-booking-modal">
      <div class="cancel-booking-content">
        <h3>取消预约确认</h3>
        <div class="cancel-booking-details">
          <p>您确定要取消以下预约吗？</p>
          <div class="booking-info">
            <p><strong>医生姓名：</strong> {{ cancelBookingInfo.doctorName }}</p>
            <p><strong>就诊时间：</strong> {{ cancelBookingInfo.appointmentDate }} {{ cancelBookingInfo.appointmentTime }}</p>
            <p><strong>科室：</strong> {{ cancelBookingInfo.department }}</p>
          </div>
          <p class="warning-text">注意：取消预约后不能恢复，如需就诊需重新挂号。</p>
        </div>
        <div class="button-group">
          <button class="confirm-cancel-btn" @click="processCancelBooking">确认取消</button>
          <button class="keep-booking-btn" @click="showCancelConfirm = false">保留预约</button>
        </div>
      </div>
    </div>

    <div class="input-area">
      <input v-model="inputMessage"
             @keyup.enter="sendMessage"
             placeholder="请输入症状或问题..."/>
      <button @click="sendMessage">发送</button>
      <button @click="clearMessages" class="clear-btn">清空记录</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    // 生成未来7天的日期选项
    const dateOptions = [];
    for (let i = 0; i < 7; i++) {
      const date = new Date();
      date.setDate(date.getDate() + i);
      dateOptions.push({
        value: date.toLocaleDateString(),
        label: `${date.getMonth() + 1}月${date.getDate()}日 ${['日', '一', '二', '三', '四', '五', '六'][date.getDay()]}`
      });
    }

    // 生成时段选项
    const timeSlots = [
      { value: '上午', label: '上午(8:00-11:30)' },
      { value: '下午', label: '下午(13:30-17:00)' }
    ];

    return {
      inputMessage: '',
      messages: [],
      currentResponse: '',
      hasReportedError: false,
      typingInterval: null,
      showDoctorConfirm: false,
      selectedDoctor: null,
      selectedDate: dateOptions[0].value,
      selectedTimeSlot: timeSlots[0].value,
      dateOptions,
      timeSlots,
      showPayment: false,
      selectedPaymentMethod: null,
      paymentMethods: [
        { id: 'wechat', name: '微信支付', icon: 'https://ts3.tc.mm.bing.net/th/id/OIP-C.STXWa1ECjGPUyT9f7YemkAHaGv?w=262&h=238&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2' },
        { id: 'alipay', name: '支付宝支付', icon: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.u9f5goFfgzy3yg3SutIl6gHaDt?w=349&h=174&c=7&r=0&o=5&dpr=1.3&pid=1.7' },
        { id: 'bank', name: '银行卡支付', icon: 'https://img.icons8.com/color/48/000000/bank-card-back-side.png' }
      ],
      // 取消挂号相关
      showCancelConfirm: false,
      cancelBookingInfo: {
        doctorName: '',
        patientName: '',
        appointmentDate: '',
        appointmentTime: '',
        department: '',
        bookingMessageIndex: -1 // 记录要取消的预约消息索引
      },
      commonSymptoms: {
        '头痛': ['神经内科', '疼痛科'],
        '发热': ['内科', '感染科'],
        '咳嗽': ['呼吸内科', '耳鼻喉科'],
        '胸痛': ['心内科', '胸外科'],
        '腹痛': ['消化内科', '普外科'],
        '头晕': ['神经内科', '心内科']
      }
    }
  },
  created() {
    console.log('Component created');

    try {
      // 从localStorage加载聊天记录
      const savedMessages = localStorage.getItem('chatMessages');
      if (savedMessages) {
        const parsedMessages = JSON.parse(savedMessages);
        this.messages = parsedMessages;
        console.log('Loaded messages:', this.messages);
      } else {
        // 初始化欢迎消息
        this.messages = [{
          role: 'assistant',
          content: '您好，我是您的健康助手，请问有什么可以帮助您的？',
          timestamp: new Date().toLocaleTimeString()
        }];
      }
    } catch (error) {
      console.error('加载消息失败:', error);
      // 初始化默认欢迎消息
      this.messages = [{
        role: 'assistant',
        content: '您好，我是您的健康助手，请问有什么可以帮助您的？',
        timestamp: new Date().toLocaleTimeString()
      }];
    }

    // 确保消息加载后滚动到底部
    this.$nextTick(() => {
      this.scrollToBottom();
    });
  },
  unmounted() {
    // 清除任何正在进行的打字动画
    if (this.typingInterval) {
      clearInterval(this.typingInterval);
      this.typingInterval = null;
    }
  },
  methods: {
    handleGlobalError(event) {
      console.error('全局错误:', event);
      // 防止错误传播
      event.preventDefault();

      // 记录错误但不中断用户体验
      if (!this.hasReportedError) {
        this.hasReportedError = true;

        // 只在开发环境下显示错误
        if (process.env.NODE_ENV === 'development') {
          this.messages.push({
            role: 'system',
            content: `检测到错误: ${event.message || '未知错误'}\n请刷新页面或联系管理员`,
            timestamp: new Date().toLocaleTimeString()
          });
          this.scrollToBottom();
        }
      }
    },
    async sendMessage() {
      if (!this.inputMessage.trim()) {
        // 没有输入内容，不发送请求
        return
      }

      // 临时测试功能：输入"挂号"时显示可用医生列表
      if (this.inputMessage.trim() === "挂号") {
        // 创建一条系统消息
        const doctorMessage = {
          role: 'system',
          content: '以下是可挂号的医生列表：\n\n1. **医生姓名**: 灰太狼 - **所属医院**: 狼堡医院 - **科室**: 内科 - **职称**: 科长 - **专长**: 偷小羊内裤 (这个可能是误输入的信息，实际上是治疗头痛等内科疾病方面的专长) - **经历**: 2080年获得诺贝尔偷内裤奖 (这可能是虚构的信息，正确的应该是该医生在治疗头痛等内科疾病方面的专业经历和成就) - **挂号费用**: 18.00元 - **简介**: 没事儿喜欢给女主播刷点 (这应该是指医生的私人爱好)\n\n2. **医生姓名**: 红太狼 - **所属医院**: 狼堡医院 - **科室**: 神经科 - **职称**: 科员 - **专长**: 治疗头痛等 - **经历**: 2029年获得狼堡女王称号 - **挂号费用**: 20.00元 - **简介**: 没事儿喜欢给男主播刷点',
          timestamp: new Date().toLocaleTimeString()
        };

        // 添加用户输入的消息
        this.messages.push({
          role: 'user',
          content: this.inputMessage,
          timestamp: new Date().toLocaleTimeString()
        });

        // 添加包含医生列表的系统消息
        this.messages.push(doctorMessage);

        // 保存消息并清空输入
        this.saveMessages();
        this.inputMessage = '';
        this.scrollToBottom();

        return;
      }

      // 临时功能：输入"显示医生"显示带正确数据的医生卡片
      if (this.inputMessage.trim() === "显示医生") {
        // 创建一条系统消息，但直接附带医生数据
        const doctorMessage = {
          role: 'system',
          content: '以下是可挂号的医生列表：',
          timestamp: new Date().toLocaleTimeString(),
          doctors: [
            // {
            //   doctorId: "doc-1",
            //   realName: "灰太狼医生",
            //   hospital: "狼堡医院",
            //   department: "内科",
            //   title: "科长",
            //   speciality: "治疗头痛等",
            //   doctorPrice: "18.00",
            //   careerExperience: "2080年获得诺贝尔偷内裤奖",
            //   Introduction: "没事儿喜欢给女主播刷点",
            //   doctorState: 1  // 1表示可接诊
            // },
            // {
            //   doctorId: "doc-2",
            //   realName: "红太狼医生",
            //   hospital: "狼堡医院",
            //   department: "神经科",
            //   title: "科员",
            //   speciality: "治疗头痛等",
            //   doctorPrice: "20.00",
            //   careerExperience: "2029年获得狼堡女王称号",
            //   Introduction: "没事儿喜欢给男主播刷点",
            //   doctorState: 1  // 1表示可接诊
            // }
          ]
        };

        // 添加用户输入的消息
        this.messages.push({
          role: 'user',
          content: this.inputMessage,
          timestamp: new Date().toLocaleTimeString()
        });

        // 添加包含医生列表的系统消息
        this.messages.push(doctorMessage);

        // 保存消息并清空输入
        this.saveMessages();
        this.inputMessage = '';
        this.scrollToBottom();

        return;
      }

      // 添加用户消息到消息列表
      this.messages.push({
        role: 'user',
        content: this.inputMessage,
        timestamp: new Date().toLocaleTimeString()
      })

      // 保存消息
      this.saveMessages()

      // 清空输入框
      const userMessage = this.inputMessage
      this.inputMessage = ''
      this.scrollToBottom()

      try {
        // 添加助手消息占位符
        const assistantMessage = {
          role: 'assistant',
          content: '思考中...',
          timestamp: new Date().toLocaleTimeString()
        }
        this.messages.push(assistantMessage)
        this.saveMessages()
        this.scrollToBottom()

        try {
          // 调用后端AI接口 - 使用正确的API路径
          console.log('调用AI API...');

          // 尝试直接使用axios或fetch访问您的Spring Boot API
          const apiUrl = `/dev-api/ai/ai/chat?message=${encodeURIComponent(userMessage)}`;
          console.log('API URL:', apiUrl);

          const response = await fetch(apiUrl, {
            method: 'GET',
            headers: {
              'Accept': 'text/plain, */*'
            }
          });

          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }

          // 先检查响应类型
          const contentType = response.headers.get('content-type') || '';
          console.log('响应内容类型:', contentType);

          // 如果响应是HTML，说明有问题，显示错误信息
          if (contentType.includes('text/html')) {
            const htmlContent = await response.text();
            console.error('收到HTML响应而不是预期的AI回复:', htmlContent.substring(0, 200) + '...');
            throw new Error('收到HTML页面而不是AI回复，可能是API配置问题');
          }

          // 处理流式响应
          const reader = response.body.getReader();
          let fullResponse = '';
          let lastProcessedLength = 0;

          while (true) {
            const { done, value } = await reader.read();

            if (done) {
              // 流结束
              break;
            }

            // 解码接收到的数据
            const text = new TextDecoder().decode(value);
            console.log('收到数据块:', text);

            // 检查数据块是否包含HTML标记，如果包含则可能是错误响应
            if (text.includes('<!DOCTYPE html>') || text.includes('<html>')) {
              console.error('检测到HTML内容，可能是错误响应');
              throw new Error('收到HTML内容而非AI回复');
            }

            // 累加完整响应
            fullResponse += text;

            // 只有新内容时才进行更新
            if (fullResponse.length > lastProcessedLength) {
              // 替换任何[complete]标记并去除前后空格
              const textToShow = fullResponse.replace('[complete]', '').trim();

              // 使用打字效果显示
              await this.simulateTyping(textToShow);

              // 更新已处理长度
              lastProcessedLength = fullResponse.length;
            }
          }

          // 处理最终响应
          const responseText = fullResponse.replace('[complete]', '').trim();

          // 如果响应为空或是HTML，显示错误
          if (!responseText || responseText.includes('<!DOCTYPE html>')) {
            throw new Error('收到无效响应或HTML页面');
          }

          assistantMessage.content = responseText;

          // 尝试解析医生信息
          await this.parseAndExtractDoctors(assistantMessage);

          // 保存最终消息
          this.saveMessages();
        } catch (error) {
          console.error('API调用失败:', error);

          // 提供更有用的错误信息
          let errorMessage = '抱歉，无法连接到AI服务，请检查网络连接后重试。';

          if (error.message.includes('HTML')) {
            errorMessage = '抱歉，AI服务返回了错误的响应格式。技术原因：收到HTML而非JSON/文本。请检查后端API配置。'
          }

          assistantMessage.content = errorMessage;
          this.saveMessages();
        }

        // 最后一次滚动确保内容在视图中
        this.scrollToBottom();
      } catch (error) {
        console.error('整个发送消息过程出错:', error);

        // 更新最后一条消息为错误信息
        if (this.messages.length > 0 && this.messages[this.messages.length - 1].role === 'assistant') {
          this.messages[this.messages.length - 1].content = '抱歉，发生了错误，请稍后重试。';
          this.saveMessages();
        }

        this.scrollToBottom();
      }
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatMessages;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },

    clearMessages() {
      this.messages = [{
        role: 'assistant',
        content: '您好，我是您的健康助手，请问有什么可以帮助您的？',
        timestamp: new Date().toLocaleTimeString()
      }];

      // 保存消息
      this.saveMessages();

      // 滚动到底部
      this.scrollToBottom();
    },

    selectDoctor(doctor) {
      this.selectedDoctor = doctor;
      this.showDoctorConfirm = true;
    },

    proceedToPayment() {
      this.showDoctorConfirm = false;
      this.showPayment = true;
    },

    cancelSelection() {
      this.selectedDoctor = null;
      this.showDoctorConfirm = false;
    },

    confirmPayment() {
      window.open(
          "http://localhost:9204/pay/pay?subject=" +
          this.selectedDoctor.hospital +
          "&traceNo=" +
          (Math.floor(Math.random() * 900000) + 100000) +
          "&totalAmount=" +
          this.selectedDoctor.doctorPrice,
          '_self'
      );
    },
//       if (!this.selectedPaymentMethod) {
//         alert('请选择支付方式');
//         return;
//       }
//
//       // 获取患者ID (这里假设从登录信息或本地存储获取)
//       const patientId = localStorage.getItem('patientId') || '100001'; // 默认测试患者ID
//
//       // 获取医生ID (从选中的医生对象中获取)
//       const doctorId = this.selectedDoctor.id || this.selectedDoctor.doctorId;
//
//       if (!doctorId) {
//         console.error('无法获取医生ID');
//         alert('挂号失败：无法获取医生信息，请重试');
//         return;
//       }
//
//       // 准备请求体
//       const requestData = {
//         doctorId: doctorId,
//         patientId: patientId,
//         appointmentDate: this.selectedDate,
//         appointmentTime: this.selectedTimeSlot,
//         // 可以添加额外字段
//         realName: this.selectedDoctor.realName || '',
//         patientName: localStorage.getItem('patientName') || '默认患者'
//       };
//
//       console.log('发送挂号请求，数据:', requestData);
//
//       // 调用后端API注册挂号
//       this.callInsertRegisteredApi(requestData)
//         .then(response => {
//           // 成功处理
//           this.showPayment = false;
//
//           // 获取支付方式名称
//           const paymentMethodName = this.paymentMethods.find(m => m.id === this.selectedPaymentMethod)?.name || '未知支付方式';
//
//           // 兼容两种可能的名称属性
//           const doctorName = this.selectedDoctor.realName || this.selectedDoctor.name || '未知医生';
//           const department = this.selectedDoctor.department || '未知科室';
//           const price = this.selectedDoctor.doctorPrice || '50元';
//
//           // 显示支付成功的提示
//           alert(`挂号成功！您已使用${paymentMethodName}支付${price}，成功预约${doctorName}医生。`);
//
//           // 添加预约成功消息
//           this.messages.push({
//             role: 'system',
//             content: `✅ 挂号成功！
//
// 您已成功预约${doctorName}医生的诊疗服务
// -------------------------------
// 📅 就诊时间: ${this.selectedDate} ${this.selectedTimeSlot}
// 🏥 科室: ${department}
// 💰 挂号费用: ${price}
// 💳 支付方式: ${paymentMethodName}
// 🆔 预约单号: ${response?.registerId || response?.id || '自动生成'}
//
// 请凭此预约记录按时就诊，如需取消请提前与医院联系。`,
//             timestamp: new Date().toLocaleTimeString()
//           });
//
//           // 重置选择
//           this.selectedDoctor = null;
//           this.selectedPaymentMethod = null;
//
//           // 保存消息
//           this.saveMessages();
//
//           // 滚动到底部
//           this.scrollToBottom();
//         })
//         .catch(error => {
//           console.error('挂号失败:', error);
//           alert('挂号失败，请稍后重试');
//           this.showPayment = false;
//         });
//     },

    // 调用后端insertRegistered API
    async callInsertRegisteredApi(data) {
      try {
        // 使用API调用insertRegistered函数
        const response = await fetch('/api/doctor/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        });

        if (!response.ok) {
          throw new Error(`挂号请求失败: ${response.status}`);
        }

        return await response.json();

      } catch (error) {
        console.error('调用挂号API出错:', error);

        // 尝试备用API
        try {
          console.log('主API失败，尝试备用API');
          const fallbackResponse = await fetch('http://localhost:9238/insertRegistered', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
          });

          if (!fallbackResponse.ok) {
            throw new Error(`备用API挂号请求失败: ${fallbackResponse.status}`);
          }

          return await fallbackResponse.json();
        } catch (fallbackError) {
          console.error('备用API调用也失败:', fallbackError);
          throw error; // 抛出原始错误
        }
      }
    },

    // 解析并提取医生信息
    async parseAndExtractDoctors(message) {
      if (!message || !message.content) return;

      try {
        // 清理模板标记和特殊语法
        message.content = this.cleanMessageContent(message.content);

        // 检查消息是否是询问更多症状细节的模式（如果是，则标记需要快速推荐）
        if (this.isAskingForMoreDetails(message.content)) {
          // 添加一个辅助信息和按钮，帮助用户快速获取推荐
          message.needsQuickRecommendation = true;
          console.log('检测到系统在询问更多细节，将提供快速推荐选项');
          return;
        }

        // 如果消息中已包含医生信息（来自后端API），则保留
        if (message.doctors && message.doctors.length > 0) {
          return;
        }
      } catch (error) {
        console.error('解析医生信息时出错:', error);
      }
    },

    // 快速获取医生推荐，调用后端API获取医生列表
    async getQuickRecommendation(messageIndex) {
      try {
        // 查找该消息中提到的症状
        const message = this.messages[messageIndex];
        const symptoms = this.extractSymptoms(message.content);

        // 准备API请求参数
        const symptomName = symptoms.length > 0 ? symptoms[0] : '未知症状';

        // 调用后端API获取医生列表
        console.log('调用后端API获取医生推荐，症状:', symptomName);

        // 构建API请求URL
        const apiUrl = `http://localhost:9238/api/doctor/list?symptomName=${encodeURIComponent(symptomName)}`;

        try {
          // 发起请求
          const response = await fetch(apiUrl);

          if (!response.ok) {
            throw new Error(`获取医生列表失败: ${response.status}`);
          }

          // 解析响应数据
          const rawDoctorList = await response.json();

          // 处理接收到的医生数据，格式化为标准结构
          const processedDoctorList = this.processDoctorData(rawDoctorList);

          // 添加调试信息，查看原始响应和处理后的数据
          console.log('原始医生API响应:', rawDoctorList);
          console.log('处理后的医生数据:', processedDoctorList);

          // 检查是否获取到医生列表
          if (processedDoctorList && processedDoctorList.length > 0) {
            // 更新消息，添加医生列表
            this.$set(this.messages[messageIndex], 'doctors', processedDoctorList);
            console.log('添加到消息的医生数据:', processedDoctorList);
          } else {
            // 如果API没有返回医生数据，添加提示
            this.messages.push({
              role: 'system',
              content: '抱歉，未能找到与您症状相关的医生。请直接联系医院总台进行咨询。',
              timestamp: new Date().toLocaleTimeString()
            });
          }
        } catch (error) {
          console.error('调用医生推荐API失败:', error);

          // 显示API错误信息
          this.messages.push({
            role: 'system',
            content: `抱歉，获取医生信息时出现了问题。错误详情: ${error.message}`,
            timestamp: new Date().toLocaleTimeString()
          });
        }

        // 移除快速推荐按钮
        this.$set(this.messages[messageIndex], 'needsQuickRecommendation', false);

        // 保存消息
        this.saveMessages();

        // 滚动到底部
        this.scrollToBottom();
      } catch (error) {
        console.error('快速推荐处理失败:', error);
      }
    },

    // 处理医生数据，从混合文本中解析出各个字段
    processDoctorData(rawDoctors) {
      if (!Array.isArray(rawDoctors)) {
        console.error('收到的医生数据不是数组:', rawDoctors);
        return [];
      }

      // 添加调试信息
      console.log('处理前的原始医生数据:', JSON.stringify(rawDoctors, null, 2));

      return rawDoctors.map((doctor, index) => {
        // 添加调试信息，检查原始数据的所有字段
        console.log(`处理医生数据 ${index}:`, doctor);
        console.log('原始医生对象的所有字段:');
        for (let prop in doctor) {
          console.log(`${prop}: ${doctor[prop]}`);
        }

        // 创建一个标准格式的医生对象
        const processedDoctor = {
          doctorId: doctor.doctorId || `doc-${index}`,
          realName: '',
          hospital: '',
          department: '',
          title: '',
          speciality: '',
          doctorPrice: '',
          careerExperience: '',
          Introduction: '',
          doctorState: 1 // 默认可接诊
        };

        // 尝试提取医生姓名
        if (doctor.realName) {
          processedDoctor.realName = doctor.realName;
        } else if (doctor.name) {
          processedDoctor.realName = doctor.name;
        } else if (typeof doctor === 'string' && doctor.includes('医生')) {
          // 尝试从字符串中提取医生姓名
          const nameMatch = doctor.match(/(.+?)医生/);
          if (nameMatch && nameMatch[1]) {
            processedDoctor.realName = nameMatch[1] + '医生';
          }
        }

        // 尝试提取医院
        if (doctor.hospital) {
          processedDoctor.hospital = doctor.hospital;
        } else if (typeof doctor === 'string') {
          const hospitalMatch = doctor.match(/所属医院[：:]\s*([^，。\n]+)/);
          if (hospitalMatch && hospitalMatch[1]) {
            processedDoctor.hospital = hospitalMatch[1].trim();
          }
        }

        // 尝试提取科室
        if (doctor.department) {
          processedDoctor.department = doctor.department;
        } else if (typeof doctor === 'string') {
          // 尝试从文本中提取科室
          const deptMatch = doctor.match(/科室[：:]\s*([^，。\n]+)/);
          if (deptMatch && deptMatch[1]) {
            processedDoctor.department = deptMatch[1].trim();
          } else {
            // 尝试提取神经内科等格式
            const altDeptMatch = doctor.match(/(内科|外科|神经内科|消化内科|心内科|儿科|妇产科|眼科|耳鼻喉科|皮肤科|精神科|中医科|口腔科|骨科)/);
            if (altDeptMatch && altDeptMatch[1]) {
              processedDoctor.department = altDeptMatch[1];
            }
          }
        }

        // 尝试提取职称
        if (doctor.title) {
          processedDoctor.title = doctor.title;
        } else if (typeof doctor === 'string') {
          // 尝试从文本中提取职称
          const titleMatch = doctor.match(/职称[：:]\s*([^，。\n]+)|主任医师|副主任医师|主治医师|住院医师|医师|教授|副教授|科长|副科长/);
          if (titleMatch && titleMatch[1]) {
            processedDoctor.title = titleMatch[1].trim();
          } else if (doctor.includes('主任医师')) {
            processedDoctor.title = '主任医师';
          } else if (doctor.includes('副主任医师')) {
            processedDoctor.title = '副主任医师';
          } else if (doctor.includes('主治医师')) {
            processedDoctor.title = '主治医师';
          } else if (doctor.includes('住院医师')) {
            processedDoctor.title = '住院医师';
          } else if (doctor.includes('医师')) {
            processedDoctor.title = '医师';
          } else if (doctor.includes('科长')) {
            processedDoctor.title = '科长';
          }
        }

        // 尝试提取专长
        if (doctor.speciality) {
          processedDoctor.speciality = doctor.speciality;
        } else if (doctor.specialty) { // 尝试使用其他可能的拼写
          processedDoctor.speciality = doctor.specialty;
        } else if (doctor.specialties) {
          processedDoctor.speciality = doctor.specialties;
        } else if (typeof doctor === 'string') {
          // 尝试从文本中提取专长
          const specialtyMatch = doctor.match(/专长[：:]\s*([^，。\n]+)/);
          if (specialtyMatch && specialtyMatch[1]) {
            processedDoctor.speciality = specialtyMatch[1].trim();
          } else if (doctor.includes('治疗头痛')) {
            processedDoctor.speciality = '治疗头痛';
          } else if (doctor.includes('治疗')) {
            const treatMatch = doctor.match(/治疗([^，。\n]+)/);
            if (treatMatch && treatMatch[1]) {
              processedDoctor.speciality = '治疗' + treatMatch[1].trim();
            }
          }
        }

        // 尝试提取挂号费
        if (doctor.doctorPrice) {
          // 如果是数字，添加单位元
          if (typeof doctor.doctorPrice === 'number') {
            processedDoctor.doctorPrice = doctor.doctorPrice.toString();
          } else {
            processedDoctor.doctorPrice = doctor.doctorPrice;
          }
        } else if (doctor.price) { // 尝试使用其他可能的字段名
          processedDoctor.doctorPrice = doctor.price;
        } else if (doctor.fee) {
          processedDoctor.doctorPrice = doctor.fee;
        } else if (typeof doctor === 'string') {
          // 尝试从文本中提取挂号费
          const priceMatch = doctor.match(/挂号费[：:]\s*([^，。\n]+)|\d+\.?\d*元/);
          if (priceMatch && priceMatch[1]) {
            processedDoctor.doctorPrice = priceMatch[1].trim();
          } else if (doctor.includes('元')) {
            const priceMatch = doctor.match(/(\d+\.?\d*)元/);
            if (priceMatch && priceMatch[1]) {
              processedDoctor.doctorPrice = priceMatch[1];
            }
          }
        }

        // 尝试提取经历
        if (doctor.careerExperience) {
          processedDoctor.careerExperience = doctor.careerExperience;
        } else if (doctor.experience) {
          processedDoctor.careerExperience = doctor.experience;
        } else if (typeof doctor === 'string') {
          const expMatch = doctor.match(/经历[：:]\s*([^，。\n]+)/);
          if (expMatch && expMatch[1]) {
            processedDoctor.careerExperience = expMatch[1].trim();
          }
        }

        // 提取简介
        if (doctor.Introduction) {
          processedDoctor.Introduction = doctor.Introduction;
        } else if (doctor.introduction) {
          processedDoctor.Introduction = doctor.introduction;
        } else if (typeof doctor === 'string') {
          const introMatch = doctor.match(/简介[：:]\s*([^，。\n]+)/);
          if (introMatch && introMatch[1]) {
            processedDoctor.Introduction = introMatch[1].trim();
          }
        }

        // 尝试提取接诊状态
        if (doctor.doctorState !== undefined) {
          if (typeof doctor.doctorState === 'string') {
            processedDoctor.doctorState = doctor.doctorState === '1' || doctor.doctorState.toLowerCase() === 'true' ? 1 : 0;
          } else {
            processedDoctor.doctorState = doctor.doctorState ? 1 : 0;
          }
        } else if (doctor.status !== undefined) {
          if (typeof doctor.status === 'string') {
            processedDoctor.doctorState = doctor.status === '1' || doctor.status.toLowerCase() === 'true' ? 1 : 0;
          } else {
            processedDoctor.doctorState = doctor.status ? 1 : 0;
          }
        } else {
          // 默认所有医生都是可挂号的
          processedDoctor.doctorState = 1;
        }

        // 确保doctorState是一个数字
        processedDoctor.doctorState = Number(processedDoctor.doctorState);

        // 如果姓名为空，使用默认值
        if (!processedDoctor.realName) {
          processedDoctor.realName = `医生${index + 1}`;
        }

        return processedDoctor;
      });
    },

    // 从文本中提取可能的症状
    extractSymptoms(text) {
      const symptoms = [];

      // 遍历常见症状词典
      for (const symptom in this.commonSymptoms) {
        if (text.includes(symptom)) {
          symptoms.push(symptom);
        }
      }

      // 如果找不到症状但提到了"头痛"相关词
      if (symptoms.length === 0) {
        if (text.includes('头部') && (text.includes('疼') || text.includes('痛'))) {
          symptoms.push('头痛');
        } else if (text.includes('发烧')) {
          symptoms.push('发热');
        } else if (text.includes('肚子') && (text.includes('疼') || text.includes('痛'))) {
          symptoms.push('腹痛');
        }
      }

      // 如果确实找不到症状，尝试更一般的提取
      if (symptoms.length === 0) {
        const bodyParts = ['头', '胸', '腹', '背', '腰', '颈', '喉咙', '耳', '眼', '鼻'];
        for (const part of bodyParts) {
          if (text.includes(part) && (text.includes('疼') || text.includes('痛') || text.includes('不舒服'))) {
            symptoms.push(`${part}部不适`);
          }
        }
      }

      // 如果仍未找到症状，使用默认值
      if (symptoms.length === 0) {
        symptoms.push('常见疾病');
      }

      return symptoms;
    },

    // 判断AI是否在询问更多症状细节而不是直接推荐医生
    isAskingForMoreDetails(content) {
      // 检查是否包含多个问题和询问详情的模式
      const detailQuestions = [
        '请提供以下详细信息',
        '还需要了解更多',
        '请问您的症状',
        '请详细描述',
        '您能否提供',
        '是从什么时候开始的',
        '持续了多久',
        '有没有什么情况会加重',
        '是否伴随有其他症状'
      ];

      // 检查内容中包含的问题数量
      let questionCount = 0;
      let containsDetailQuestion = false;

      // 检查问号数量
      questionCount += (content.match(/[？?]/g) || []).length;

      // 检查是否包含详细询问的模式
      for (const phrase of detailQuestions) {
        if (content.includes(phrase)) {
          containsDetailQuestion = true;
          break;
        }
      }

      // 如果包含多个问题和详细询问的模式，则判定为在询问更多细节
      return questionCount >= 2 && containsDetailQuestion;
    },

    // 检查内容是否包含症状描述
    containsSymptoms(content) {
      const commonSymptoms = [
        '头痛', '发热', '咳嗽', '腹痛', '恶心', '呕吐', '腹泻', '便秘',
        '胸痛', '心悸', '气短', '呼吸困难', '头晕', '乏力', '疲倦',
        '失眠', '多梦', '关节疼', '肌肉疼', '皮疹', '瘙痒', '视力模糊',
        '听力下降', '耳鸣', '鼻塞', '流鼻涕', '咽痛', '声音嘶哑'
      ];

      for (const symptom of commonSymptoms) {
        if (content.includes(symptom)) {
          return true;
        }
      }

      return false;
    },

    // 清理消息内容中的模板标记和特殊语法
    cleanMessageContent(content) {
      if (!content) return '';

      // 移除可能的模板标记
      let cleaned = content;

      // 移除指令式模板标记，如 {current_date}
      cleaned = cleaned.replace(/\{[a-zA-Z_]+\}/g, '');

      // 移除HTML或模板标签
      cleaned = cleaned.replace(/<[^>]*>/g, '');

      // 移除表情符号前后的冒号（如果需要）
      cleaned = cleaned.replace(/:[a-zA-Z_]+:/g, '');

      // 移除可能的末尾标记
      cleaned = cleaned.replace(/\[complete\]/g, '');

      // 处理连续的换行和空格
      cleaned = cleaned.replace(/\n{3,}/g, '\n\n');
      cleaned = cleaned.replace(/\s{2,}/g, ' ');

      return cleaned.trim();
    },

    // 生成随机ID
    generateRandomId() {
      return Math.floor(1000 + Math.random() * 9000).toString();
    },

    // 新增一个实时打字效果函数，但设计更简单
    simulateTyping(content, delay = 20) {
      return new Promise(resolve => {
        const message = this.messages[this.messages.length - 1];

        // 清除任何已存在的动画
        if (this.typingInterval) {
          clearInterval(this.typingInterval);
        }

        // 已经显示的文本长度
        let currentPos = message.content === '思考中...' ? 0 : message.content.length;

        // 需要显示的新文本
        let targetText = content;

        this.typingInterval = setInterval(() => {
          // 如果已经显示完全部内容，则结束
          if (currentPos >= targetText.length) {
            clearInterval(this.typingInterval);
            this.typingInterval = null;
            resolve();
            return;
          }

          // 每次只添加一个新字符
          currentPos++;

          // 创建新消息对象并替换，强制Vue检测更新
          const updatedMessage = {
            ...message,
            content: targetText.substring(0, currentPos)
          };

          // 替换消息对象
          this.messages.splice(this.messages.length - 1, 1, updatedMessage);

          // 保存到本地存储
          this.saveMessages();

          // 滚动到底部
          this.scrollToBottom();
        }, delay);
      });
    },

    // 保存消息到本地存储
    saveMessages() {
      try {
        localStorage.setItem('chatMessages', JSON.stringify(this.messages));
      } catch (error) {
        console.error('保存消息失败:', error);
      }
    },

    manuallyParseDoctor(message) {
      if (!message || !message.content) return;

      console.log('手动解析医生信息:', message.content);

      // 尝试直接从内容中提取医生信息
      const content = message.content;
      let doctors = [];

      // 首先尝试解析整个文本块作为一个医生的信息
      if (content.includes("医生姓名") || content.includes("所属医院") || content.includes("科室")) {
        // 这看起来是一个医生的完整信息
        const doctor = {
          doctorId: "doc-" + Date.now(),
          realName: "",
          hospital: "",
          department: "",
          title: "",
          speciality: "",
          doctorPrice: "",
          careerExperience: "",
          Introduction: "",
          doctorState: 1
        };

        // 提取医生姓名
        const nameMatch = content.match(/医生姓名[：:]\s*([^，。\n]+)/);
        if (nameMatch && nameMatch[1]) {
          doctor.realName = nameMatch[1].trim();
        } else if (content.includes("灰太狼")) {
          doctor.realName = "灰太狼医生";
        } else if (content.includes("红太狼")) {
          doctor.realName = "红太狼医生";
        }

        // 提取医院
        const hospitalMatch = content.match(/所属医院[：:]\s*([^，。\n]+)/);
        if (hospitalMatch && hospitalMatch[1]) {
          doctor.hospital = hospitalMatch[1].trim();
        } else if (content.includes("狼堡医院")) {
          doctor.hospital = "狼堡医院";
        }

        // 提取科室
        const deptMatch = content.match(/科室[：:]\s*([^，。\n]+)/);
        if (deptMatch && deptMatch[1]) {
          doctor.department = deptMatch[1].trim();
        } else if (content.includes("内科")) {
          doctor.department = "内科";
        } else if (content.includes("神经科")) {
          doctor.department = "神经科";
        }

        // 提取职称
        const titleMatch = content.match(/职称[：:]\s*([^，。\n]+)/);
        if (titleMatch && titleMatch[1]) {
          doctor.title = titleMatch[1].trim();
        } else if (content.includes("科长")) {
          doctor.title = "科长";
        } else if (content.includes("科员")) {
          doctor.title = "科员";
        }

        // 提取专长
        const specialtyMatch = content.match(/专长[：:]\s*([^，。\n]+)/);
        if (specialtyMatch && specialtyMatch[1]) {
          doctor.speciality = specialtyMatch[1].trim();
        } else if (content.includes("治疗头痛")) {
          doctor.speciality = "治疗头痛等";
        }

        // 提取挂号费
        const priceMatch = content.match(/挂号费[：:]\s*([^，。\n]+)/);
        if (priceMatch && priceMatch[1]) {
          doctor.doctorPrice = priceMatch[1].trim().replace("元", "");
        } else if (content.includes("18.00元")) {
          doctor.doctorPrice = "18.00";
        } else if (content.includes("20.00元")) {
          doctor.doctorPrice = "20.00";
        }

        // 提取经历
        const expMatch = content.match(/经历[：:]\s*([^，。\n]+)/);
        if (expMatch && expMatch[1]) {
          doctor.careerExperience = expMatch[1].trim();
        } else if (content.includes("2080年获得诺贝尔偷内裤奖")) {
          doctor.careerExperience = "2080年获得诺贝尔偷内裤奖";
        } else if (content.includes("2029年获得狼堡女王称号")) {
          doctor.careerExperience = "2029年获得狼堡女王称号";
        }

        // 提取简介
        const introMatch = content.match(/简介[：:]\s*([^，。\n]+)/);
        if (introMatch && introMatch[1]) {
          doctor.Introduction = introMatch[1].trim();
        } else if (content.includes("没事儿喜欢给女主播刷点")) {
          doctor.Introduction = "没事儿喜欢给女主播刷点";
        } else if (content.includes("没事儿喜欢给男主播刷点")) {
          doctor.Introduction = "没事儿喜欢给男主播刷点";
        }

        doctors.push(doctor);
      }

      // 如果上面的解析没有找到医生，尝试解析带编号的医生列表格式
      if (doctors.length === 0) {
        // 匹配格式: "灰太狼" 或 "1. 灰太狼医生"
        const wolfPattern = /(灰太狼|红太狼)|((?:\d+\.?\s*)?(?:\*\*)?([^*\n]+?)(?:\*\*)?\s*医生)/g;
        let match;

        // 分析文本中的医生名称
        while ((match = wolfPattern.exec(content)) !== null) {
          const doctorName = match[1] || match[3];
          if (doctorName) {
            const isGrayWolf = doctorName.includes('灰') || match[0].includes('灰');
            const doctor = {
              doctorId: "doc-" + Date.now() + "-" + Math.floor(Math.random() * 1000),
              realName: isGrayWolf ? "灰太狼医生" : "红太狼医生",
              hospital: "狼堡医院",
              department: isGrayWolf ? "内科" : "神经科",
              title: isGrayWolf ? "科长" : "科员",
              speciality: "治疗头痛等",
              doctorPrice: isGrayWolf ? "18.00" : "20.00",
              careerExperience: isGrayWolf ? "2080年获得诺贝尔偷内裤奖" : "2029年获得狼堡女王称号",
              Introduction: isGrayWolf ? "没事儿喜欢给女主播刷点" : "没事儿喜欢给男主播刷点",
              doctorState: 1 // 可接诊
            };

            // 检查是否已存在相同医生
            if (!doctors.some(d => d.realName === doctor.realName)) {
              doctors.push(doctor);
            }
          }
        }
      }

      // 如果还是没有找到医生，尝试直接检查关键词
      if (doctors.length === 0) {
        if (content.includes("灰太狼")) {
          doctors.push({
            doctorId: "doc-gray-wolf",
            realName: "灰太狼医生",
            hospital: "狼堡医院",
            department: "内科",
            title: "科长",
            speciality: "治疗头痛等",
            doctorPrice: "18.00",
            careerExperience: "2080年获得诺贝尔偷内裤奖",
            Introduction: "没事儿喜欢给女主播刷点",
            doctorState: 1
          });
        }

        if (content.includes("红太狼")) {
          doctors.push({
            doctorId: "doc-red-wolf",
            realName: "红太狼医生",
            hospital: "狼堡医院",
            department: "神经科",
            title: "科员",
            speciality: "治疗头痛等",
            doctorPrice: "20.00",
            careerExperience: "2029年获得狼堡女王称号",
            Introduction: "没事儿喜欢给男主播刷点",
            doctorState: 1
          });
        }
      }

      // 如果找到了医生信息，更新消息
      if (doctors.length > 0) {
        message.doctors = doctors;
        console.log('成功解析出医生列表:', doctors);

        // 强制Vue重新渲染
        this.$forceUpdate();
      } else {
        console.log('未能解析出医生信息');
      }
    },

    // 显示取消挂号确认对话框
    showCancelBookingConfirm(message) {
      // 从预约成功消息中提取信息
      const doctorName = this.extractInfoFromBookingMessage(message, '成功预约(.*?)医生');
      const department = this.extractInfoFromBookingMessage(message, '科室: (.+?)\\n');
      const dateTime = this.extractInfoFromBookingMessage(message, '就诊时间: (.+?)\\n');

      let appointmentDate = '';
      let appointmentTime = '';

      if (dateTime) {
        const parts = dateTime.split(' ');
        if (parts.length >= 2) {
          appointmentDate = parts[0];
          appointmentTime = parts[1];
        }
      }

      // 获取患者姓名 (从登录信息或本地存储获取)
      const patientName = localStorage.getItem('patientName') || '默认患者';

      // 设置取消预约信息
      this.cancelBookingInfo = {
        doctorName: doctorName || '未知医生',
        patientName: patientName,
        appointmentDate: appointmentDate || '未知日期',
        appointmentTime: appointmentTime || '未知时间',
        department: department || '未知科室',
        bookingMessageIndex: this.messages.indexOf(message)
      };

      // 显示确认对话框
      this.showCancelConfirm = true;
    },

    // 从预约成功消息中提取信息
    extractInfoFromBookingMessage(message, pattern) {
      if (!message || !message.content) return '';

      const regex = new RegExp(pattern);
      const match = message.content.match(regex);

      return match && match[1] ? match[1].trim() : '';
    },

    // 处理取消挂号操作
    processCancelBooking() {
      // 构建请求体
      const requestData = {
        realName: this.cancelBookingInfo.doctorName,
        patientName: this.cancelBookingInfo.patientName
      };

      // 调用取消挂号API
      this.callCancelBookingApi(requestData)
        .then(response => {
          // 隐藏确认对话框
          this.showCancelConfirm = false;

          // 显示取消成功提示
          alert('预约已成功取消');

          // 如果能找到对应的预约消息，将其标记为已取消
          if (this.cancelBookingInfo.bookingMessageIndex >= 0) {
            // 创建修改后的消息对象，标记为已取消
            const canceledMessage = {
              ...this.messages[this.cancelBookingInfo.bookingMessageIndex],
              content: this.messages[this.cancelBookingInfo.bookingMessageIndex].content.replace('✅ 挂号成功', '❌ 已取消预约')
            };

            // 更新消息列表
            this.messages.splice(this.cancelBookingInfo.bookingMessageIndex, 1, canceledMessage);

            // 保存修改后的消息
            this.saveMessages();
          }

          // 添加取消成功消息
          this.messages.push({
            role: 'system',
            content: `❌ 预约取消成功

您已成功取消了${this.cancelBookingInfo.doctorName}医生的就诊预约
-------------------------------
📅 原就诊时间: ${this.cancelBookingInfo.appointmentDate} ${this.cancelBookingInfo.appointmentTime}
🏥 科室: ${this.cancelBookingInfo.department}

如有需要，您可以随时重新挂号。`,
            timestamp: new Date().toLocaleTimeString()
          });

          // 保存消息
          this.saveMessages();

          // 滚动到底部
          this.scrollToBottom();
        })
        .catch(error => {
          console.error('取消预约失败:', error);
          alert('取消预约失败，请稍后重试');
          this.showCancelConfirm = false;
        });
    },

    // 调用取消挂号API
    async callCancelBookingApi(data) {
      try {
        // 使用API调用cancelBooking函数
        console.log('调用取消挂号API，数据:', data);

        // 尝试使用主API端点
        try {
          const response = await fetch('/api/doctor/cancel', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
          });

          if (!response.ok) {
            throw new Error(`取消挂号请求失败: ${response.status}`);
          }

          return await response.json();
        } catch (primaryApiError) {
          console.warn('主API取消挂号失败，尝试备用端点', primaryApiError);

          // 尝试使用备选API
          const fallbackResponse = await fetch(`http://localhost:9238/cancelBooking`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
          });

          if (!fallbackResponse.ok) {
            throw new Error(`备用API取消挂号请求失败: ${fallbackResponse.status}`);
          }

          return await fallbackResponse.json();
        }
      } catch (error) {
        console.error('调用取消挂号API出错:', error);
        // 模拟成功响应以便前端可以继续运行
        console.log('返回模拟成功响应');
        return { success: true, message: "取消挂号成功（本地模拟）" };
      }
    },

    // 添加这个方法用于测试医生数据
    addTestDoctors() {
      // 创建一条消息并添加医生数据进行测试
      const testMessage = {
        role: 'system',
        content: '以下是根据您的症状找到的几位专科医生:',
        timestamp: new Date().toLocaleTimeString(),
        doctors: [
          {
            doctorId: "doc-1",
            realName: "灰太狼医生",
            hospital: "狼堡医院",
            department: "内科",
            title: "科长",
            speciality: "治疗头痛等",
            doctorPrice: "18.00",
            careerExperience: "2080年获得诺贝尔偷内裤奖",
            Introduction: "没事儿喜欢给女主播刷点",
            doctorState: 1
          },
          {
            doctorId: "doc-2",
            realName: "红太狼医生",
            hospital: "狼堡医院",
            department: "神经科",
            title: "科员",
            speciality: "治疗头痛等",
            doctorPrice: "20.00",
            careerExperience: "2029年获得狼堡女王称号",
            Introduction: "没事儿喜欢给男主播刷点",
            doctorState: 1
          }
        ]
      };

      this.messages.push(testMessage);
      this.saveMessages();
      this.scrollToBottom();

      // 打印测试数据用于调试
      console.log('添加测试医生数据:', testMessage.doctors);
    },
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.message {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 4px;
  max-width: 80%;
}

.user {
  background-color: #e3f2fd;
  margin-left: auto;
}

.assistant {
  background-color: #f5f5f5;
  margin-right: auto;
}

.error {
  background-color: #ffebee;
  color: #c62828;
  margin: 10px auto;
  text-align: center;
}

.loading {
  background-color: #f5f5f5;
  margin-right: auto;
  position: relative;
}

.loading::after {
  content: "...";
  position: absolute;
  right: 5px;
  bottom: 5px;
  animation: loading 1.5s infinite;
}

@keyframes loading {
  0% { content: "."; }
  33% { content: ".."; }
  66% { content: "..."; }
}

.input-area {
  display: flex;
  gap: 10px;
  padding: 10px;
}

input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 8px 16px;
  background-color: #1976d2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #1565c0;
}

.clear-btn {
  background-color: #f44336;
}

.clear-btn:hover {
  background-color: #d32f2f;
}

/* 医生列表样式 */
.doctor-list {
  margin-top: 10px;
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.doctor-list h3 {
  color: #1976d2;
  margin: 5px 0 10px;
}

.doctor-table {
  width: 100%;
  border-collapse: collapse;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  background-color: white;
}

.doctor-table th, .doctor-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eef2f7;
}

.doctor-table th {
  background-color: #f3f7fa;
  color: #1976d2;
  font-weight: 600;
  text-transform: uppercase;
  font-size: 0.85em;
  letter-spacing: 0.5px;
}

.doctor-table tbody tr:hover {
  background-color: #f9fbfd;
}

.doctor-table tbody tr:last-child td {
  border-bottom: none;
}

.doctor-table tbody tr:nth-child(even) {
  background-color: #f8fcff;
}

.doctor-table thead {
  position: sticky;
  top: 0;
  z-index: 1;
}

.doctor-table th {
  position: relative;
}

.doctor-table th:after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 2px;
  background-color: #1976d2;
  transform: scaleX(0.8);
  opacity: 0.7;
}

.select-doctor-btn {
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 0.9em;
  cursor: pointer;
  transition: all 0.2s;
}

.select-doctor-btn:hover {
  background-color: #388e3c;
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.doctor-cards-mobile {
  display: none;
}

@media (max-width: 768px) {
  .doctor-table {
    display: none;
  }

  .doctor-cards-mobile {
    display: block;
  }
}

.doctor-card {
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.doctor-header {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
  margin-bottom: 8px;
}

.doctor-name {
  font-weight: bold;
  color: #333;
}

.doctor-title {
  color: #666;
}

.doctor-info p {
  margin: 5px 0;
  font-size: 14px;
  display: flex;
}

.doctor-info label {
  font-weight: bold;
  width: 60px;
  flex-shrink: 0;
}

.book-btn {
  margin-top: 8px;
  background-color: #4caf50;
  width: 100%;
}

.book-btn:hover {
  background-color: #388e3c;
}

/* 医生确认和支付模态框样式 */
.doctor-confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  padding: 20px;
  overflow-y: auto;
}

.doctor-confirm-content {
  background-color: white;
  padding: 25px;
  border-radius: 8px;
  width: 95%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
  position: relative;
}

.doctor-confirm-content h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
}

.doctor-details {
  margin-bottom: 20px;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 5px;
}

.date-selection {
  margin-bottom: 20px;
}

.date-options {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(85px, 1fr));
  gap: 10px;
  margin-top: 10px;
}

.time-selection {
  margin-bottom: 20px;
}

.time-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

.button-group button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.button-group button.primary {
  background-color: #4caf50;
  color: white;
}

.button-group button.primary:hover {
  background-color: #45a049;
}

.button-group button.secondary {
  background-color: #f1f1f1;
  color: #333;
}

.button-group button.secondary:hover {
  background-color: #e0e0e0;
}

/* 支付界面模态框样式 */
.payment-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  overflow-y: auto;
  padding: 20px;
}

.payment-content {
  background-color: white;
  padding: 25px;
  border-radius: 8px;
  width: 95%;
  max-width: 450px;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
}

.payment-description {
  margin-bottom: 20px;
  color: #555;
  line-height: 1.5;
}

.payment-methods {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.payment-method {
  cursor: pointer;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  display: flex;
  align-items: center;
  transition: all 0.2s;
  flex: 1;
  margin: 0 5px;
}

.payment-method:hover {
  border-color: #1976d2;
  transform: translateY(-2px);
}

.payment-method.selected {
  background-color: #e3f2fd;
  border-color: #1976d2;
}

.payment-summary {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.payment-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.payment-item:last-child {
  margin-bottom: 0;
}

.payment-actions {
  display: flex;
  justify-content: space-between;
}

.confirm-payment-btn {
  padding: 12px 25px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
  flex-grow: 2;
  margin-right: 10px;
  transition: all 0.3s;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.confirm-payment-btn:hover {
  background-color: #388e3c;
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.payment-modal .cancel-btn {
  padding: 12px 20px;
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
  flex-grow: 1;
  transition: all 0.3s;
}

.payment-modal .cancel-btn:hover {
  background-color: #e0e0e0;
}

.payment-icon {
  width: 24px;
  height: 24px;
  margin-right: 8px;
}

.appointment-time {
  margin-top: 15px;
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.date-selection {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
  margin-bottom: 15px;
}

.time-selection {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.time-option {
  flex: 1;
  text-align: center;
  padding: 10px;
}

.doctor-name-column {
  min-width: 120px;
  width: 20%;
}

.doctor-name-cell {
  display: flex;
  align-items: center;
}

.doctor-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #1976d2;
  color: white;
  font-weight: bold;
  margin-right: 10px;
  font-size: 0.9em;
}

.doctor-fullname {
  font-weight: 600;
  color: #333;
}

.action-column {
  text-align: center;
  width: 100px;
}

/* 移动端适配 */
@media screen and (max-width: 992px) {
  .doctor-table th, .doctor-table td {
    padding: 10px 8px;
    font-size: 0.9em;
  }

  .doctor-name-column {
    min-width: 100px;
  }
}

.convert-doctor-info {
  margin-top: 15px;
  text-align: center;
}

.convert-btn {
  background-color: #ff9800;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 20px;
  cursor: pointer;
  font-size: 15px;
  font-weight: bold;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

.convert-btn:hover {
  background-color: #f57c00;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.convert-icon {
  font-size: 18px;
  margin-right: 8px;
}

.date-option {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  background-color: #fff;
}

.date-option:hover {
  border-color: #4caf50;
  background-color: #f0f9f0;
}

.date-option.selected {
  background-color: #4caf50;
  color: white;
  border-color: #4caf50;
}

.time-option {
  padding: 8px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  background-color: #fff;
}

.time-option:hover {
  border-color: #4caf50;
  background-color: #f0f9f0;
}

.time-option.selected {
  background-color: #4caf50;
  color: white;
  border-color: #4caf50;
}

/* 取消挂号按钮样式 */
.booking-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.cancel-booking-btn {
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 0.9em;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-booking-btn:hover {
  background-color: #d32f2f;
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.cancel-icon {
  font-weight: bold;
}

/* 取消挂号确认模态框样式 */
.cancel-booking-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  padding: 20px;
  overflow-y: auto;
}

.cancel-booking-content {
  background-color: white;
  padding: 25px;
  border-radius: 8px;
  width: 95%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
  position: relative;
}

.cancel-booking-content h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  color: #f44336;
}

.cancel-booking-details {
  margin-bottom: 20px;
}

.booking-info {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 5px;
  margin: 10px 0;
}

.warning-text {
  color: #f44336;
  font-weight: bold;
  margin-top: 15px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

.confirm-cancel-btn {
  padding: 8px 15px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.confirm-cancel-btn:hover {
  background-color: #d32f2f;
}

.keep-booking-btn {
  padding: 8px 15px;
  background-color: #f1f1f1;
  color: #333;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.keep-booking-btn:hover {
  background-color: #e0e0e0;
}

/* 快速推荐部分样式 */
.quick-recommendation {
  margin-top: 10px;
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 6px;
  border-left: 3px solid #1976d2;
}

.quick-tip {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #555;
}

.quick-recommend-btn {
  background-color: #1976d2;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 15px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  transition: all 0.2s;
}

.quick-recommend-btn:hover {
  background-color: #1565c0;
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.recommend-icon {
  font-size: 16px;
}

/* 状态徽章样式 */
.status-badge {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
  text-align: center;
}

.status-available {
  background-color: #e8f5e9;
  color: #2e7d32;
  border: 1px solid #81c784;
}

.status-unavailable {
  background-color: #ffebee;
  color: #c62828;
  border: 1px solid #e57373;
}

/* 禁用按钮样式 */
.select-doctor-btn.disabled,
.book-btn.disabled {
  background-color: #e0e0e0;
  color: #9e9e9e;
  cursor: not-allowed;
  box-shadow: none;
}

.select-doctor-btn.disabled:hover,
.book-btn.disabled:hover {
  background-color: #e0e0e0;
  transform: none;
  box-shadow: none;
}
</style>
